import { Modal, Radio, RadioChangeEvent, Table } from 'antd';
import { useEffect, useState } from 'react';
import { ColumnType } from 'antd/lib/table';
import { DeviceHeartbeatItem } from '@/pages/data-manage/deviceHeartbeat/types';
import { getHeartbeatDataList } from '@/pages/data-manage/deviceHeartbeat/service';
import { DeviceIdentifyItem } from '@/pages/data-manage/deviceIdentify/types';
import { getIdentifyDataList } from '@/pages/data-manage/deviceIdentify/service';

interface DeviceDetailProps {
  deviceNo: string;
  visible: boolean;
  onClose: () => void;
}

interface PaginationConfig {
  page: number;
  pageSize: number;
  total: number;
}

export default (props: DeviceDetailProps) => {

  const { visible, onClose, deviceNo } = props;
  const [heartbeatDataList, setHeartbeatDataList] = useState<DeviceHeartbeatItem[] | undefined>(undefined)
  const [identifyDataList, setIdentifyDataList] = useState<DeviceIdentifyItem[] | undefined>(undefined)
  const [loading, setLoading] = useState<boolean>(false);
  const [type, setType] = useState<number>(0);
  const [pageObject, setPageObject] = useState<PaginationConfig>({
    page: 1,
    pageSize: 10,
    total: 0,
  });

  const columnsHeartbeats: ColumnType<DeviceHeartbeatItem>[] = [
    {
      title: '产品名',
      dataIndex: 'product',
    },
    {
      title: 'ip地址',
      dataIndex: 'ip',
    },
    {
      title: 'ipV6地址',
      dataIndex: 'ip_v6',
    },
    {
      title: '设备sn',
      dataIndex: 'sn',
    },
    {
      title: '泊位列表',
      dataIndex: 'parking_number',
    },
    {
      title: '上报时间',
      dataIndex: 'report_time',
    },
  ];

  const columnsIdentifies: ColumnType<DeviceIdentifyItem>[] = [
    {
      title: '唯一识别码',
      dataIndex: 'reco_id',
      width: 110
    },
    {
      title: '结果序列号',
      dataIndex: 'serial',
      width: 105
    },
    {
      title: '触发类型',
      dataIndex: 'trigger_type',
      width: 100
    },
    {
      title: '协议版本',
      dataIndex: 'protocol',
      width: 100
    },
    {
      title: '视频通道号',
      dataIndex: 'chnlid',
      width: 110
    },
    {
      title: 'ip地址',
      dataIndex: 'ip',
      width: 120
    },
    {
      title: '设备sn',
      dataIndex: 'sn',
      width: 170
    },
    {
      title: '报警状态',
      dataIndex: 'alarm_status',
      width: 100
    },
    {
      title: '车身颜色',
      dataIndex: 'car_color',
      width: 100
    },
    {
      title: '车辆类型',
      dataIndex: 'car_type',
      width: 100
    },
    {
      title: '车型置信度',
      dataIndex: 'car_type_source',
      width: 110
    },
    {
      title: '车头车尾信息',
      dataIndex: 'car_pos_pos',
      width: 120
    },
    {
      title: '车位状态',
      dataIndex: 'parking_state',
      width: 100
    },
    {
      title: '泊位id',
      dataIndex: 'zone_id',
      width: 100
    },
    {
      title: '泊位号',
      dataIndex: 'zone_name',
      width: 100
    },
    {
      title: '车辆序号',
      dataIndex: 'zone_index',
      width: 100
    },
    {
      title: '区域类型',
      dataIndex: 'zone_type',
      width: 100
    },
    {
      title: '车牌颜色',
      dataIndex: 'plate_color',
      width: 100
    },
    {
      title: '车牌置信度',
      dataIndex: 'plate_confidence',
      width: 110
    },
    {
      title: '车牌清晰度',
      dataIndex: 'plate_sharpness',
      width: 110
    },
    {
      title: '车牌近期识别过',
      dataIndex: 'recent_plate',
      width: 130
    },
    {
      title: '车牌号',
      dataIndex: 'plate',
      width: 100
    },
    {
      title: '车牌类型',
      dataIndex: 'plate_type',
      width: 100
    },
    {
      title: '识别对象状态',
      dataIndex: 'covered_event',
      width: 120
    },
    {
      title: '识别组id',
      dataIndex: 'group_id',
      width: 100
    },
    {
      title: '识别标志',
      dataIndex: 'reco_flag',
      width: 100
    },
    {
      title: '识别id',
      dataIndex: 'group_reco_id',
      width: 100
    },
    {
      title: '识别时间',
      dataIndex: 'reco_time',
      width: 210
    },
    {
      title: '订单评分',
      dataIndex: 'order_score',
      width: 100
    },
    {
      title: '订单状态',
      dataIndex: 'force_level_flag',
      width: 100
    },
    {
      title: '重启触发',
      dataIndex: 'restart',
      width: 100
    },
    {
      title: '识别结果类型',
      dataIndex: 'data_type',
      width: 120
    },
    {
      title: '识别图片',
      dataIndex: 'img_url',
      width: 100
    },
    {
      title: '路段id',
      dataIndex: 'road_id',
      width: 180
    },
    {
      title: '路段名',
      dataIndex: 'road_name',
      width: 150
    },
  ];

  const request = async (
    deviceNo: string,
    type: number,
    page?: number,
    pageSize?: number,
  ): Promise<any> => {
    let data;
    if (type === 0) {
      data = await getHeartbeatDataList({
        device_no: deviceNo,
        page: page || 1,
        pageSize: pageSize || pageObject.pageSize || 10
      })
    } else {
      data = await getIdentifyDataList({
        device_no: deviceNo,
        page: page || 1,
        pageSize: pageSize || pageObject.pageSize || 10
      })
    }
    if (data.success) {
      setPageObject({ ...pageObject, total: data.total || 0, page: page || 1 });
    } else {
      setPageObject({ ...pageObject, total: 0, page: 1 });
    }
    return data;
  }

  useEffect(() => {
    if (!deviceNo) throw new Error('设备号 不能为空');
    setLoading(true);
    request(deviceNo, 0, 1)
      .then((res) => {
        if (res.success && res.data !== null) {
          setHeartbeatDataList(res.data);
          setLoading(false);
        }
      })
      .finally(() => { });
  }, []);

  const handleReload = async (page?: number) => {
    setLoading(true);
    request(deviceNo, type, page)
      .then((res) => {

        if (res.success && res.data !== null) {
          switch (type) {
            case 0: // 心跳数据
              setHeartbeatDataList(res.data);
              setIdentifyDataList(undefined);
              setLoading(false);
              break;
            case 1: // 识别结果
              setIdentifyDataList(res.data);
              setHeartbeatDataList(undefined);
              setLoading(false);
              break;
            default:
              break;
          }
        }
      })
      .finally(() => { });
  };

  const radioChange = (e: RadioChangeEvent) => {
    const selectedType: number = e.target.value;
    setType(selectedType);

    setLoading(true);
    setPageObject({ ...pageObject, page: 1, pageSize: 10 });

    request(deviceNo, selectedType)
      .then((res) => {
        if (res.success && res.data !== null) {
          switch (selectedType) {
            case 0: // 心跳数据
              setHeartbeatDataList(res.data);
              setIdentifyDataList(undefined);
              setLoading(false);
              break;
            case 1: // 识别结果
              setIdentifyDataList(res.data);
              setHeartbeatDataList(undefined);
              setLoading(false);
              break;
            default:
              break;
          }
        }
      })
      .finally(() => { });
  };

  return (
    <Modal
      title={<div>设备{deviceNo} &nbsp;历史数据</div>}
      open={visible}
      width={1200}
      footer={null}
      centered
      destroyOnClose
      onOk={() => onClose()}
      onCancel={() => onClose()}
      afterClose={() => onClose()}
    >

      <span style={{ marginRight: '10px' }}>记录类型选择:</span>
      <Radio.Group name="radio_group" defaultValue={0} onChange={radioChange}>
        <Radio value={0}>心跳数据</Radio>
        <Radio value={1}>识别结果</Radio>
      </Radio.Group>

      {heartbeatDataList && (
        <Table
          columns={columnsHeartbeats}
          dataSource={heartbeatDataList}
          loading={loading}
          style={{ marginTop: '20px' }}
          pagination={{
            showQuickJumper: false,
            showSizeChanger: false,
            ...pageObject,
            pageSize: 10,
            onChange: (page, pageSize) => {
              setPageObject({ ...pageObject, page, pageSize: pageSize || 10 });
              handleReload(page);
            },
          }}
        />

      )}

      {identifyDataList && (
        <Table
          columns={columnsIdentifies}
          dataSource={identifyDataList}
          loading={loading}
          style={{ marginTop: '20px' }}
          scroll={{ x: 1200, y: 1000 }}
          pagination={{
            showQuickJumper: false,
            showSizeChanger: false,
            ...pageObject,
            onChange: (page, pageSize) => {
              setPageObject({ ...pageObject, page, pageSize: pageSize || 10 });
              handleReload(page);
            },
          }}
        />

      )}

    </Modal>
  );
};
